package com.hpradip.android.accessNumberSpeedDialer;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.util.Log;

public class ContactsProvider {

	private ContentProviderClient client;
	private ContentResolver contentResolver;

	public List<Contact> loadContacts(Context context) {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(context);
		contentResolver = context.getContentResolver();
		client = contentResolver
				.acquireContentProviderClient(ContactsContract.Data.CONTENT_URI);

		String[] projection = new String[] { Data.RAW_CONTACT_ID,
				Data.PHOTO_ID, Data.DISPLAY_NAME, Phone.NUMBER,
				Phone.TYPE, Phone.LABEL, Data.TIMES_CONTACTED };

		String[] display_options = context.getResources().getStringArray(
				R.array.contacts_display_options_values);

		String sortByTimesContacted = Data.TIMES_CONTACTED + " DESC, "
				+ Data.DISPLAY_NAME + " ASC";
		String sortQuery = sortByTimesContacted;

		if (preferences
				.getString(
						context.getResources().getString(
								R.string.key_default_contacts_view),
						display_options[1]).trim()
				.equalsIgnoreCase(display_options[0]))
			sortQuery = sortByTimesContacted;

		if (preferences
				.getString(
						context.getResources().getString(
								R.string.key_default_contacts_view),
						display_options[1]).trim()
				.equalsIgnoreCase(display_options[1]))
			sortQuery = Data.DISPLAY_NAME + " ASC";

		Cursor cursor;
		try {
			cursor = client.query(Data.CONTENT_URI, projection, Data.MIMETYPE
					+ "='" + Phone.CONTENT_ITEM_TYPE + "'", null,
					sortQuery);
			return getColumnData(cursor);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d("ContactsProvider", e.getMessage());
			return new ArrayList<Contact>();
		} finally {
			client.release();
		}
	}

	private List<Contact> getColumnData(Cursor cur) {
		List<Contact> contacts = new ArrayList<Contact>();
		if (cur.moveToFirst()) {

			int rawId;
			String photoId;
			Bitmap photo;
			String name;
			String phoneNumber;
			String timesContacted;

			int rawIdColumn = cur.getColumnIndex(Data.RAW_CONTACT_ID);
			int photoIdColumn = cur.getColumnIndex(Data.PHOTO_ID);
			int nameColumn = cur.getColumnIndex(Data.DISPLAY_NAME);
			int phoneColumn = cur.getColumnIndex(Phone.NUMBER);
			int timesContactedColumn = cur.getColumnIndex(Data.TIMES_CONTACTED);

			String imagePath;

			do {
				// Get the field values
				rawId = cur.getInt(rawIdColumn);
				photoId = cur.getString(photoIdColumn);
				name = cur.getString(nameColumn);
				phoneNumber = cur.getString(phoneColumn);
				timesContacted = cur.getString(timesContactedColumn);

				Contact contact = new Contact();
				contact.setId(rawId);
				contact.setName(name);
				contact.setNumber(phoneNumber);
				contact.setTimesCalled(Integer.parseInt(timesContacted));
				contact.setPhotoId(photoId);
				// contact.setPhoto(photo);

				photo = loadContactPhoto(contentResolver, rawId);

				if (photo != null) {
					contact.setPhoto(photo);
				}

				contacts.add(contact);
			} while (cur.moveToNext());

			cur.close();
		}

		return contacts;
	}
	
	public static Bitmap loadContactPhoto(ContentResolver cr, int id) {
	    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
	    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
	    if (input == null) {
	        return null;
	    }
	    return BitmapFactory.decodeStream(input);
	}


	public static void UpdateTimesContacted(Context context, int contactId) {
		ContentResolver contentResolver = context.getContentResolver();
		Contacts.markAsContacted(contentResolver, contactId);
	}
}
